home *** CD-ROM | disk | FTP | other *** search
- Path: rcp6.elan.af.mil!rscernix!danpop
- From: danpop@mail.cern.ch (Dan Pop)
- Newsgroups: comp.lang.c
- Subject: Re: Do you have ever pass structures?
- Date: 22 Feb 96 13:21:00 GMT
- Organization: CERN European Lab for Particle Physics
- Message-ID: <danpop.824995260@rscernix>
- References: <4ge8mi$qjm@srvr1.engin.umich.edu> <4ggs0r$2bt@newshost.cyberramp.net>
- NNTP-Posting-Host: ues5.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
-
- In <4ggs0r$2bt@newshost.cyberramp.net> sinan@cyberramp.net (John Noland) writes:
-
- >Anyway, I'll give you this much (but you should still read K&R), C passes
- >all arguments except arrays by value - a copy of a variable is passed to
- >a function on the stack. (You could argue - correctly - that arrays are
- >not really an exception because C passes the pointer to the first element
- >by value, but that isn't the way it's usually presented).
-
- Arrays are an exception, indeed, because they're not passed as arguments
- to functions at all :-) In a value context, an array name decays to a
- pointer to the first element and that pointer is passed using the single
- method of passing arguments supported by C: by value.
-
- However, there is a workaround for passing arrays by value: wrap them in
- a structure! Whether this is a good idea or not is up to every programmer
- to decide for his particular application.
-
- Another point: some implementations don't really pass structures by value,
- they only pretend to! They caller makes a local copy of the struct and
- passes a pointer to that copy. The callee transparently dereferences
- that pointer to access the struct members. When the callee returns, the
- caller discards the copy. This has an interesting consequence for broken
- code, like this:
-
- /* void foo(const struct bar *p); this prototype is not in the scope
- of the caller */
- struct bar baz;
- foo(baz);
-
- With a prototype for foo in scope, the compiler would detect the error.
- If such a prototype doesn't exist (maybe because the compiler is old
- enough to not support prototypes but new enough to pass structures
- "by value") the compiler will silently accept the code and the code will
- "work" as intended because the caller actually sends a pointer to a
- copy of baz and the callee expects a pointer to struct bar.
-
- The code will "misteriously" crash and burn when ported to a different
- platform, which actually passes structures by value.
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-